import cv2
import numpy as np

# 建立图片展示窗口
cv2.namedWindow("wind")
# 读取图片
img_origin = cv2.imread("1.jpg")
# 高斯滤波降噪
img_gaus = cv2.GaussianBlur(img_origin, (1, 1), 2)
# 转换为灰阶图像
img_gray = cv2.cvtColor(img_gaus, cv2.COLOR_BGR2GRAY)
# 使用Canny算子绘制轮廓
img_canny = cv2.Canny(img_gaus, 50, 150)
# 展示Canny算子计算结果
cv2.imshow("wind", img_canny)
cv2.waitKey(0)
# 查找Canny结果的边缘
contours, _ = cv2.findContours(img_canny, cv2.RETR_TREE, cv2.CHAIN_APPROX_TC89_KCOS)
# 创建图像副本并绘制边缘查找结果
img_draw = img_origin.copy()
cv2.drawContours(img_draw, contours, -1, (0, 0, 255), 1)
cv2.imshow("wind", img_draw)
cv2.waitKey(0)
# 查找最大边缘
# area = []
# for k in range(len(contours)):
#    area.append(cv2.contourArea(contours[k]))
# max_idx = np.argmax(np.array(area))
# del area
# 填充所有的轮廓
mask = np.ones_like(img_origin)
for k in range(len(contours)):
    cv2.drawContours(mask, contours, k, (255, 255, 255), cv2.FILLED)
# 将mask转为二值图
_, img_mask = cv2.threshold(mask, 127, 255, cv2.THRESH_BINARY)
# 展示最大轮廓漫水填充结果（mask）
# cv2.imshow("wind", img_mask)
# cv2.waitKey(0)
# 将最大轮廓漫水填充图像作为mask抠出
img_masked = np.zeros(img_origin.shape, np.uint8)
for row in range(img_mask.shape[0]):
    for col in range(img_mask.shape[1]):
        if (img_mask[row, col] - [0]).all():
            img_masked[row, col] = img_origin[row, col]
        else:
            img_masked[row, col] = 0
# 展示最终结果
cv2.imshow("wind", img_masked)
cv2.waitKey(0)
# 退出并清理所有窗口
cv2.destroyAllWindows()
